#include "dialogFileManager.h"
#include "ui_dialogFileManager.h"
#ifdef Q_OS_ANDROID


DialogFileManager::DialogFileManager(int type, QWidget*parent) : QDialog(parent)
{

    ui = new Ui::dialogFileManager;
    ui->setupUi(this);


    // 初始化取值
    _type = type;
    _page = 0;
    _resultPath = "";
    _resultType = "";

    // 创建对象
    _widget_smbLogin = new DialogSMBLogin(this);
    _widget_smbLogin->close();
    _fileSpacer = new QSpacerItem(40, 40, QSizePolicy::Expanding);
    _dirSpacer = new QSpacerItem(40, 40, QSizePolicy::Expanding);

    // 存储路径列表
    _storageList_button.append(ui->button_local);
    _storageList_button.append(ui->button_USB);
    _storageList_button.append(ui->button_SMB);

    if(type == 0){
        ui->pushButton_select->hide();
    }

    // 初始化文件夹列表
    for(int i = 0; i < _storageList_button.size(); i ++){
        _dirList_path.append(new QStack<QString>);
        _dirList_path[i]->append("/");
    }
    _basePath = "/storage/emulated/0/";
    _usbPath = JNIManager::I().getUSBPath();


    connect(_widget_smbLogin, SIGNAL(sig_connectSuccess(QString)), this, SLOT(on_newStorage_connected(QString)));

    //ui->button_USB->hide();

    loadPage();

}

DialogFileManager::~DialogFileManager(){
}

QString DialogFileManager::getResult(){
    return _resultPath;
}

void DialogFileManager::init(){

}


QString DialogFileManager::getCurrentDir(){

    QString res = "/";
    if(_page <= 1){
        foreach(QString dir, *(_dirList_path[_page])){
            res.append(dir);
        }
    }else{
        int i = 0;
        foreach(QString dir, *(_dirList_path[_page])){
            if(i >= 2){
                res.append(dir);
            }
            i ++;
        }
    }
    return res;
}


void DialogFileManager::on_newStorage_connected(QString ip){

    _page = 2;
    _dirList_path[2]->clear();
    _dirList_path[2]->append("/");
    loadPage();
    return;
}


void DialogFileManager::loadPage(){

    ui->label_info->setText("");
    ui->button_root->setText(_storageList_button[_page]->text());
    // 按钮颜色更新
    for(int i = 0; i < _storageList_button.size(); i ++){
        if(i == _page){
            _storageList_button[i]->setStyleSheet("border:none; border-bottom:3px solid #2F42CD;");
        }else{
            _storageList_button[i]->setStyleSheet("border:none;");
        }
    }
    if(_page == 2){
        ui->button_add->show();
    }else{
        ui->button_add->hide();
    }


    QStringList fileList;
    if(_page == 0){
        QString dir = _basePath + getCurrentDir();
        fileList = JNIManager::I().getFileList(dir);
        if(fileList.size() == 0){
            ui->label_info->setText("文件夹拒绝访问");
            _dirList_path[_page]->pop();
        }else{
            loadFolderPage();
            loadFilePage(fileList);
        }
    }else if(_page == 1){
        if(_dirList_path[_page]->size() == 1){
            fileList = _usbPath;
            loadFolderPage();
            loadFilePage(fileList);
        }else{
            QString dir = getCurrentDir();
            fileList = JNIManager::I().getFileList(dir);
            if(fileList.size() == 0){
                ui->label_info->setText("文件夹拒绝访问");
                _dirList_path[_page]->pop();
            }else{
                loadFolderPage();
                loadFilePage(fileList);
            }
        }
    }else{                                                      // 网络路径
        QString dir = getCurrentDir();
        if(_dirList_path[_page]->size() == 1){
            fileList = SMBManager::I().getIpList();
            loadFolderPage();
            loadFilePage(fileList);
        }else{
            // 打开网络路径时需要等待加载
            ui->label_info->setText("加载中");
            QTimer::singleShot(100, [this, dir](){
                QString ip = (*_dirList_path[2])[1];
                ip = ip.remove('/');
                QStringList fileList = SMBManager::I().getFileList(ip, dir);
                if(fileList.size() == 0){
                    ui->label_info->setText("加载失败");
                    _dirList_path[_page]->pop();        // 回退上一层文件夹
                }else{
                    ui->label_info->setText("");
                    loadFolderPage();
                    loadFilePage(fileList);
                }
            });
        }
    }

}


void DialogFileManager::loadFilePage(QStringList fileList){
    // 刷新文件列表
    int item_num = 0;
    for(int i = 0; i < fileList.size(); i ++){
        if(i >= _fileList_widget.size()){
            _fileList_widget.append(new FileItemWidget(this));
            ui->layout_file->addWidget(_fileList_widget.back());
            connect(_fileList_widget.back(), SIGNAL(sig_FileItemClicked(QString, FileItemWidget::FileType)), this, SLOT(on_file_clicked(QString,FileItemWidget::FileType)));
            connect(_fileList_widget.back(), SIGNAL(sig_FileItemOperate(QString)), this, SLOT(on_ip_delete(QString)));
        }
        _fileList_widget[i]->setText(fileList[i]);
        if(_fileList_widget[i]->getText().size()==0 ||    // 隐藏条件：1. 文件名为空 2. 文件名以'.'开头 3. /storge/emulated和/storage/self
           _fileList_widget[i]->getText()[0] == '.' ||
           (_page==1 && _dirList_path[_page]->size()==1 && (_fileList_widget[i]->getText()=="emulated/" ||_fileList_widget[i]->getText()=="self/"))){
            _fileList_widget[i]->hide();
        }else{
            _fileList_widget[i]->show();
            item_num ++;
        }
        if(_dirList_path[_page]->size() == 1){
            if(_page == 1){
                _fileList_widget[i]->setFileType(FileItemWidget::USB);
            }else if(_page == 2){
                _fileList_widget[i]->setFileType(FileItemWidget::IP);
            }
        }

    }
    ui->pannel_file->setFixedHeight(item_num * 45);
    for(int i = fileList.size(); i < _fileList_widget.size(); i ++){
        _fileList_widget[i]->hide();
    }

}

void DialogFileManager::loadFolderPage(){
    // 刷新文件夹列表
    for(int i = 0; i < _dirList_path[_page]->size(); i ++){
        if(i >= _dirList_button.size()){
            _dirList_button.append(new TextButton(this));
            ui->layout_dir->addWidget(_dirList_button.back());
            _dirList_button.back()->setMinimumWidth(5);
            _dirList_button.back()->setStyleSheet("QPushButton{color:rgba(0, 0, 0, 0.9);text-align : right; background-color: rgba(255, 255, 255, 0); border:none}");
            connect(_dirList_button.back(), SIGNAL(clickedText(QString)), this, SLOT(on_dir_clicked(QString)));
        }
        _dirList_button[i]->setText((*_dirList_path[_page])[i]);
        _dirList_button[i]->show();
    }
    for(int i = (*_dirList_path[_page]).size(); i < _dirList_button.size(); i ++){
        _dirList_button[i]->hide();
    }
    ui->layout_dir->removeItem(_fileSpacer);
    ui->layout_dir->addSpacerItem(_fileSpacer);

}


void DialogFileManager::on_file_clicked(QString text, FileItemWidget::FileType type){      // 点击文件：返回或者加载新的文件夹

    if(type != FileItemWidget::FILE){     // 文件夹
        if(type == FileItemWidget::IP){
            qDebug() << "点击IP";
            _dirList_path[_page]->push(text + "/");
        }else{
            qDebug() << "点击文件夹";
            _dirList_path[_page]->push(text);
        }

        loadPage();
    }else{                      // 文件
        if(_type == 0){

            _resultPath = "/" + getCurrentDir() + "/" + text;
            if(_page == 0){
                _resultPath = _basePath + _resultPath;
            }
            if(_page == 2){
                try {
                    QString ip = (*_dirList_path[2])[1];
                    ui->label_info->setText("正在打开文件");
                    QTimer::singleShot(100, [this, ip]{
                        _resultPath = SMBManager::I().createSMBPath(ip, _resultPath);
                        this->close();
                    });
                } catch (...) {
                    ui->label_info->setText("打開失敗");
                }
            }else{
                qDebug() << "打开文件路径" << _resultPath;
                this->close();
            }

        }else if(_type == 1){

        }
    }
}

void DialogFileManager::on_dir_clicked(QString text){       // 点击目录：更新目录位置

    while(!_dirList_path[_page]->empty() && _dirList_path[_page]->top() != text){
        _dirList_path[_page]->pop();
    }
    loadPage();
}


void DialogFileManager::on_pushButton_select_clicked()
{
    if((_page == 2) && (*_dirList_path[2]).size() == 1){     // 用户选择网络路径或USB路径根目录
        ui->label_info->setText("请选择文件夹");
        return;
    }
    if((_page == 1) && (*_dirList_path[1]).size() == 1){     // 用户选择网络路径或USB路径根目录
        ui->label_info->setText("请选择文件夹");
        return;
    }



    _resultPath = getCurrentDir();
    if(_page == 0){
        _resultPath = _basePath + _resultPath;
    }
    if(_page == 2){
        try {
            QString ip = (*_dirList_path[2])[1];
            ui->label_info->setText("加載中");
            QTimer::singleShot(100, [this, ip]{
                _resultPath = SMBManager::I().createSMBPath(ip, _resultPath);
                this->close();
            });

        }catch (...) {
            ui->label_info->setText("打開失敗");
        }
    }else{
        this->close();
    }

}

void DialogFileManager::on_pushButton_cancel_clicked(){
    _resultPath = "";
    this->close();
}


void DialogFileManager::on_button_local_clicked(){
    _page = 0;
    loadPage();
}

void DialogFileManager::on_button_USB_clicked(){
    _page = 1;
    loadPage();
}

void DialogFileManager::on_button_SMB_clicked(){
    _page = 2;
    loadPage();
}

void DialogFileManager::on_button_root_clicked(){
    _dirList_path[_page]->clear();
    _dirList_path[_page]->append("/");
    loadPage();
}

void DialogFileManager::on_button_add_clicked(){
    _widget_smbLogin->exec();
}


void DialogFileManager::on_button_close_clicked(){
    _resultPath = "";
    this->close();
}

void DialogFileManager::on_ip_delete(QString ip){
    QMessageBox msg;
    msg.setText("确认删除该网络地址吗");
    msg.setStandardButtons(QMessageBox::Cancel | QMessageBox::Yes);
    int ret = msg.exec();
    if(ret == QMessageBox::Cancel){
        return;
    }
    SMBManager::I().delConnection(ip);
    loadPage();
}

#endif

